<template>
	<view class="login" :style="'height: '+height+'px'">
		<u--image :showLoading="true" src="/static/img/logo.png" width="216rpx" height="60rpx"></u--image>
		<u-button type="success" text="微信一键登录" open-type="getUserInfo" withCredentials="true" lang="zh_CN"  @click="wxGetUserInfo" :customStyle="{marginTop:'100rpx'}"></u-button>
		
		<u-popup :show="show" @close="show = false" >
			<view class="edit-box">
				<view class="up-box">
					<u-icon name="setting" color="#f56c6c" size="28"></u-icon>
					<view style="margin-left: 20rpx;">
						小程序 申请
					</view>
				</view>
				<view class="text-box">
					<view class="title">
						获取您的昵称、头像
					</view>
					<view class="sub-title">
						让用户正常登录，提升辨识度
					</view>
				</view>
				<view class="edit-avatar" >
					<button class="avatar2" type="primary" style="border:0;" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" plain="true">
						<u-avatar :src="avatar" size="60"></u-avatar>
					</button>
				</view>
				<view class="edit-avatar" style="margin: 30rpx 0;">
					<input type="nickname" v-model="nickname" style="font-size: 28rpx;color: #666666;flex: 1;" placeholder="请输入昵称"  @blur="getNickname" />
				</view>
				
				<view class="btn-box">
					<button class="auth" type="warn"  @click="refuse" lang="zh_CN">拒绝</button>
					<button class="auth" type="primary" @click="updateUserInfo()" lang="zh_CN">允许</button>
				</view>
					
			</view>
		</u-popup>
		
		<u-popup :show="show" @close="show = false" >
			<view class="edit-box">
				<view class="up-box">
					<u-icon name="setting" color="#f56c6c" size="28"></u-icon>
					<view style="margin-left: 20rpx;">
						小程序 申请
					</view>
				</view>
				<view class="text-box">
					<view class="title">
						获取您的昵称、头像
					</view>
					<view class="sub-title">
						让用户正常登录，提升辨识度
					</view>
				</view>
				<view class="edit-avatar" >
					<button class="avatar2" type="primary" style="border:0;" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" plain="true">
						<u-avatar :src="avatar" size="60"></u-avatar>
					</button>
				</view>
				<view class="edit-avatar" style="margin: 30rpx 0;">
					<input type="nickname" v-model="nickname" style="font-size: 28rpx;color: #666666;flex: 1;" placeholder="请输入昵称"  @blur="getNickname" />
				</view>
				
				<view class="btn-box">
					<button class="auth" type="warn"  @click="refuse" lang="zh_CN">拒绝</button>
					<button class="auth" type="primary" @click="updateUserInfo()" lang="zh_CN">允许</button>
				</view>
					
			</view>
		</u-popup>
		
		<u-popup  :show="mobshow" @close="mobshow=false">
			<u-button type="primary" text="获取微信手机号" customStyle="margin-top:30px;margin-bottom:30px" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"></u-button>
		</u-popup>
	</view>
</template>

<script>
	import {baseUrl,baseApi} from '@/common/config'
	export default {
		data() {
			return {
				mobshow: false,
				title: "用户隐私保护提示",
				desc1: "感谢您使用本产品，您使用本产品前应当仔细阅读并同意",
				urlTitle: "《小程序隐私保护指引》",
				desc2: "当您点击同意并开始使用产品服务时，即表示你已理解并同意该条款内容，该条款将对您产生法律约束力。如您拒绝，将无法更好的体验产品。",
				privateContent:'',
				show: false,
				pshow: false,
				height:0,
				token:'',
				code:'',
				nickname:'',
				defalutAvatar: "http://yongqiu.host109.rundev.cn/uploads/images/default-avatar.png",
				avatar: '',
			};
		},
		onLoad() {
			var _this = this
			uni.getSystemInfo({
				success:function(res){
					_this.$nextTick(function() {
						_this.height = res.windowHeight
						console.log("_height",_this.height);
					});
					
				}
			})
			this.avatar = this.defalutAvatar;
			uni.getPrivacySetting({
			      success: res => {
			        console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
			        if (res.needAuthorization) {
			          // 需要弹出隐私协议
			          // this.getPrivateContentFun();
					  // this.$refs.popup.show(); 
					  this.pshow = true;
			        } else {
			        
			        }
			      },
			      fail: () => {},
			      complete: () => {}
			    })
			uni.hideShareMenu({
				menus:['shareAppMessage', 'shareTimeline']
			})
			var token = uni.getStorageSync("LOGIN_TOKEN_KEY");
			if (token) {
				uni.switchTab({
					url: "/pages/mine/index"
				});
			}
			this.getWxCode();
			
		},
		methods:{
			getPhoneNumber(e) {
				const {
					encryptedData,
					iv
				} = e.detail;
				const params = {
					code: this.code,
					encryptedData: encryptedData,
					iv
				}
				if (encryptedData) {
					uni.$u.http.post('/User/getWxPhone',params).then(async res =>{
						this.handleback()
					}).catch(err => {
					})
				}
			},
			openPrivacyContract() {
				uni.openPrivacyContract({});
			},
			handleAgreePrivacyAuthorization(e) {
				getApp().globalData.showPrivacy = false;
				this.pshow = false;
			},
			handleDisagree() {
				// this.$refs.popup.close();
				this.pshow = false;
			},
			topriv(id){
				console.log("id",id);
				uni.navigateTo({
					url:"/pages/notice/detail?id=" + id
				})
			},
			handleOpenPrivacyContract() {
			    // 打开隐私协议页面
			    uni.openPrivacyContract({
			      success: () => {}, // 打开成功
			      fail: () => {}, // 打开失败
			      complete: () => {}
			    })
			  },
			async onChooseAvatar(e){
				var _this = this;
				const { avatarUrl } = e.detail;
				const result = await this.uploadFilePromise(avatarUrl);
				this.avatar=baseUrl + result;
				
			},
			async uploadFilePromise(url) {
				var _this = this;
				return new Promise((resolve, reject) => {
					// console.log('url',url);
					let a = uni.uploadFile({
						url: baseApi + '/Upload/upload', //仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'center_img'
						},
						header: {
							 "Authorization": _this.token
						},
						success: (res) => {
							var data = JSON.parse(res.data)
							setTimeout(() => {
								resolve(data.data)
							}, 1000)
						}
					});
				})
			},
			getNickname(e){
				this.nickname=e.detail.value;
			},
			getWxCode(){
				var _this = this;
				uni.login({
					success(res) {
						// resolve(res.code);
						_this.code = res.code;
						console.log('code',res.code);
					},
				
					fail(res) {
						reject(res);
					}
				
				});
			},
			go(url) {
				uni.navigateTo({
					url
				})
			},
			handleback(){
				
				var backurl = uni.getStorageSync('BACK_URL_OBJ');
				if(backurl){
					if(backurl.type == 'navi'){
						uni.redirectTo({
							url: backurl.url
						})
					}else if(backurl.type == "tab"){
						uni.switchTab({
							url:  backurl.url
						})
					}
					return;
				}
				
				uni.switchTab({
					url: "/pages/mine/index"
				});
			},
			updateUserInfo(){
				const {avatar,nickname,defalutAvatar} = this;
				if(avatar == defalutAvatar){
					uni.$u.toast("请选择头像")
				}
				
				if(!nickname){
					uni.$u.toast("请输入昵称!")
				}
				
				uni.$u.http.post('/User/updateAvatarAndNickname',{avatar,nickname}).then(async res =>{
					this.show = false;
					if(res.mob_show){
						this.mob_show = true;
						return;
					}
					this.handleback()
				}).catch(err => {
				})
			},
			refuse(){
				this.show = false;
				uni.navigateBack()
			},
			wxGetUserInfo() {
				var vm = this;
				uni.getUserProfile({
					desc: "登录",
					fail: (e)=>{
						console.log("fail e",e);
					},
					success: (e) => {
						console.log('getUserProfile',e);
						if (e.errMsg == "getUserProfile:ok") {
							//return;
							console.log('getUserProfile',e);
							var data = {
								code: vm.code,
								iv: e.iv,
								encryptedData: e.encryptedData,
								signature: e.signature
							}
							uni.$u.http.post('/User/miniLogin',data).then(async res =>{
								// console.log('res',res);
								uni.setStorageSync("LOGIN_TOKEN_KEY", res.token);
								vm.token = res.token;
								if(res.update && res.update == 1){
									if(res.avatar){
										vm.avatar = res.avatar;
									}
									if(res.nickname){
										vm.nickname = res.nickname;
									}
									vm.show = true;
									return false;
								}else if(res.update == 2){
									vm.getWxCode();
									vm.mobshow = true;
									return false
								}
								
								this.handleback()
								
							}).catch(err => {
							})
							 
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
.login{
	padding: 100rpx 30rpx;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.edit-box {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding: 40rpx 20rpx;
		.up-box {
			width: 100%;
			height: 60rpx;
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			font-weight: 700;
			font-size: 34rpx;
			
		}
		.text-box {
			width: 100%;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			margin-bottom: 20rpx;
			.title{
				font-weight: 700;
				font-size: 38rpx;
				margin: 30rpx 0;
				color: #000
			}
			.sub-title{
				font-size: 30rpx;
				color: #999;
			}
		}
		.edit-avatar{
			 text-align: center;
			 .tit{
				 font-size: 28rpx;
				 padding: 10px 0;
			 }
			 .avatar2{
				display: flex;
				justify-content: center;
				align-items: center;
			 }
		}
		.btn-box {
			width: 100%;
			display: flex;
			flex-direction: row;
			.auth{
				margin: 0 40rpx;
				flex: 1;
				border-radius: 50rpx;
				font-size: 35rpx;
			}
		}
		
	}
	
	.priv-content{
		padding: 20rpx;
	}
	.pri-con{
		display: flex;
		flex-direction: row;
		justify-content: center;
		.pri-item{
			color: #3c9cff;
			margin-right: 20rpx;
		}
	}
	
	.popup-box {
		display: flex;
		// width: 80vw;
		// height: 40vh;
		overflow: hidden;
		background: #ffffff;
		padding: 30rpx;
		border-radius: 24rpx;
 
		.weui-half-screen-dialog__hd {
			font-size: 48rpx;
			// font-family: Source Han Sans CN-Bold, Source Han Sans CN;
			font-weight: bold;
			color: #000000;
			line-height: 56rpx;
		}
 
		.weui-half-screen-dialog__bd {
			margin-top: 48rpx;
			text-indent: 2em;
			.weui-half-screen-dialog__tips {
				font-size: 28rpx;
				// font-family: Source Han Sans CN-Normal, Source Han Sans CN;
				font-weight: 400;
				color: #000000;
				line-height: 33rpx;
			}
		}
 
		.weui-half-screen-dialog__ft {
			display: flex;
			flex-direction: row;
			justify-content: space-evenly;
			align-items: center;
			margin-top: 48rpx;
			.weui-btn {
				padding: 0 60rpx;
				margin: 0;
				background: none;
				font-size: 32rpx;
				// font-family: Source Han Sans CN-Normal, Source Han Sans CN;
				font-weight: 400;
				color: #000000;
				line-height: 80rpx;
				// border: 2rpx solid #8BC21F;
			}
 
			.agree {
				color: #ffffff;
				background: linear-gradient(90deg, #8BC21F 0%, #7AB30A 100%);
			}
		}
 
		.color-8BC21F {
			color: #8BC21F !important;
		}
	}
		
		
</style>
